import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  ListView,
  StyleSheet,
  TouchableOpacity,
  DeviceEventEmitter,
  Platform,
} from 'react-native';
import _ from 'lodash';
import PxToDp from '../../../utils/PxToDp';
import FontFamilys from '../../../utils/FontFamilys';
import ModalExt from '../../Public/ModalExt';
import ChooseBrand from '../../../containers/ChooseBrandContainer';
import ChooseModel from '../../../containers/ChooseModelContainer';
import ChooseStyle from '../../../containers/ChooseStyleContainer';
import Loading from '../../Public/Loading';

import { selectingCompareCar, fetchCompareCars, fetchCarModels, fetchCarStyles } from '../../../actions/communicateAction';

const cars = [
  {
    id: 23945,
    number: 1,
    modeldesc: '普拉多 2016款 2.7L 手动版',
  },
  {
    id: 26560,
    number: 2,
    modeldesc: '锐界 2016款 EcoBoost 245 两驱精锐型 5座',
  },
  {
    id: 23961,
    number: 3,
    modeldesc: '撼路者 2016款 2.0T 汽油自动两驱菁英版',
  },
];

class Recommend extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  _selected(recommend) {
    const { car, dispatch, carInfo } = this.props;
    if (!_.isEqual(car.id, recommend.id)) {
      const com = { id: recommend.id, modeldesc: recommend.modeldesc };
      const ids = this.getCompareCarIds(carInfo.car, com);
      dispatch(selectingCompareCar(com));
      dispatch(fetchCompareCars(ids));
    }
    this.props.onPress();
  }

  getCompareCarIds(defaultCar, compareCar) {
    return compareCar && compareCar.id ?
    [].concat(defaultCar.id, compareCar.id) :
    [].concat(defaultCar.id);
  }

  render() {
    const { rowData } = this.props;
    return (
      <View style={[styles.bgColor, styles.flex]}>
        <TouchableOpacity
          activeOpacity={0.6}
          style={[styles.row, styles.recomendList]}
          onPress={() => this._selected(rowData)}
        >
          <Image
            source={require('../../../img/oCaricon.png')}
            style={[styles.icon]}
          />
          <View style={[styles.listRight]}>
            <Text style={[styles.right1]}>推荐车型{rowData.number}</Text>
            <Text style={[styles.right2]}>{rowData.modeldesc}</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

class AddCarModel extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    this.state = {
      brandVisible: false,
      modelVisible: false,
      styleVisible: false,
      dataSource: ds,
    };
  }

  _goBack() {
    this.props.navigator.pop();
  }

  _goChooseBrand() {
    const { dispatch } = this.props;
    this.props.navigator.push({
      component: ChooseBrand,
      passProps: { dispatch },
    });
  }

  _completed() {
    DeviceEventEmitter.emit('showToast', '添加车型成功！');
    const { carInfo, subBrand, carStyle, dispatch } = this.props;
    if (subBrand && carStyle) {
      const com = { id: carStyle.id, modeldesc: `${subBrand.text} ${carStyle.text}` };
      const ids = this.getCompareCarIds(carInfo.car, com);
      dispatch(fetchCompareCars(ids));
      dispatch(selectingCompareCar(com));
      this.props.navigator.pop();
    }
  }

  _brandVisible() {
    this.setState({ brandVisible: false });
  }

  _modelVisible() {
    this.setState({ modelVisible: false });
  }

  _styleVisible(visible) {
    this.setState({ styleVisible: visible });
  }

  _getStyle() {
    this._styleVisible(true);
    const { carModel, dispatch } = this.props;
    dispatch(fetchCarStyles(carModel.id));
  }

  _chooseCarModels(carId) {
    this.setState({ modelVisible: true });
    this.props.dispatch(fetchCarModels(carId));
  }

  getCompareCarIds(defaultCar, compareCar) {
    return compareCar && compareCar.id ?
    [].concat(defaultCar.id, compareCar.id) :
    [].concat(defaultCar.id);
  }

  render() {
    const {
      subBrand,
      carModels,
      carModel,
      carStyles,
      carStyle,
      car,
      carInfo,
      dispatch,
   } = this.props;

    console.log('this.props:', this.props);
    return (
      <View style={[styles.bgColor, styles.flex, styles.titleTop]}>
        <View style={[styles.row, styles.header]}>
          <TouchableOpacity
            activeOpacity={0.6}
            onPress={() => this._goBack()}
          >
            <Image
              source={require('../../../img/go_back.png')}
              style={[styles.backIcon]}
            />
          </TouchableOpacity>
          <Text style={[styles.title]}>添加车型</Text>
          <TouchableOpacity
            activeOpacity={0.6}
            onPress={() => this._completed()}
          >
            <Text style={[styles.completedText]}>完成</Text>
          </TouchableOpacity>
        </View>
        <View style={[styles.wrapper]}>
          <View style={[styles.edit]}>
            <TouchableOpacity
              activeOpacity={0.6}
              style={[styles.row, styles.list, { justifyContent: 'space-between', paddingRight: PxToDp(16) }]}
              onPress={() => this._goChooseBrand()}
            >
              <View style={[styles.row, { alignItems: 'center' }]}>
                <Image
                  source={require('../../../img/oBrand.png')}
                  style={[styles.icon]}
                />
                <View style={[styles.listRight]}>
                  <Text style={[styles.right1]}>品牌</Text>
                  {
                    subBrand.text ?
                      <Text style={[styles.right2, { color: '#333' }]}>{subBrand.text}</Text> :
                      <Text style={[styles.right2]}>请选择品牌</Text>
                  }
                </View>
              </View>
              <Image
                source={require('../../../img/h_next.png')}
                style={[styles.icon]}
              />
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={0.6}
              style={[styles.row, styles.list]}
              onPress={() => this._chooseCarModels(subBrand.id)}
            >
              <Image
                source={require('../../../img/oCaricon.png')}
                style={[styles.icon]}
              />
              <View style={[styles.listRight]}>
                <Text style={[styles.right1]}>车型</Text>
                {
                    carModel.text ?
                      <Text style={[styles.right2, { color: '#333' }]}>{carModel.text}</Text> :
                      <Text style={[styles.right2]}>请选择车型</Text>
                  }
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={0.6}
              style={[styles.row, styles.list]}
              onPress={() => this._getStyle()}
            >
              <Image
                source={require('../../../img/oStyle.png')}
                style={[styles.icon]}
              />
              <View style={[styles.listRight]}>
                <Text style={[styles.right1]}>款式</Text>
                {
                  carStyle && carStyle.text
                  ?
                    <Text style={[styles.right2]}>{carStyle.text}</Text>
                  :
                    <Text style={[styles.right2]}>请选择款式</Text>

                }

              </View>
            </TouchableOpacity>
          </View>
          <View style={[styles.recomendWrapper]}>
            <ListView
              dataSource={this.state.dataSource.cloneWithRows(cars)}
              renderRow={rowData => <Recommend
                rowData={rowData}
                car={car}
                carInfo={carInfo}
                dispatch={dispatch}
                onPress={() => this._goBack()}
              />}
            />
          </View>
        </View>
        <ModalExt
          onRequestClose={() => this._modelVisible(false)}
          animationType={'slide'}
          transparent
          visible={this.state.modelVisible}
        >


          {
            carModels
            ?
              <ChooseModel
                title="选择型号"
                dispatch={dispatch}
                carModels={carModels}
                onPress={() => this._modelVisible(false)}
              />
            :
              <Loading />
          }


        </ModalExt>
        <ModalExt
          onRequestClose={() => this._styleVisible(false)}
          animationType={'slide'}
          transparent
          visible={this.state.styleVisible}
        >
          {
            carStyles
            ?
              <ChooseStyle
                title="选择款式"
                dispatch={dispatch}
                carStyles={carStyles}
                car={car}
                onPress={() => this._styleVisible(false)}
              />
            :
              <Loading />
          }

        </ModalExt>
      </View>
    );
  }
 }

const styles = StyleSheet.create({
  bgColor: {
    backgroundColor: '#f8f8fb',
    alignItems: 'center',
  },
  flex: {
    flex: 1,
  },
  row: {
    flexDirection: 'row',
  },
  header: {
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
    height: PxToDp(44),
    paddingLeft: PxToDp(16),
    paddingRight: PxToDp(26),
    backgroundColor: '#fff',
  },
  backIcon: {
    width: PxToDp(14),
    height: PxToDp(22),
  },
  title: {
    color: '#121212',
    fontSize: PxToDp(18),
    fontWeight: 'bold',
    fontFamily: FontFamilys(),
  },
  completedText: {
    color: '#418cff',
    fontSize: PxToDp(14),
    fontFamily: FontFamilys(),
  },
  wrapper: {
    flex: 1,
    width: '100%',
    paddingLeft: PxToDp(10),
    paddingRight: PxToDp(10),
    paddingTop: PxToDp(18),
  },
  edit: {
    width: PxToDp(355),
    height: PxToDp(192),
    paddingLeft: PxToDp(28),
    backgroundColor: '#fff',
    borderColor: '#f3f4f6',
    borderWidth: 1,
  },
  list: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    width: PxToDp(327),
    height: PxToDp(64),
    borderColor: '#ececec',
    borderBottomWidth: 1,
  },
  icon: {
    width: PxToDp(24),
    height: PxToDp(24),
  },
  listRight: {
    justifyContent: 'center',
    alignItems: 'flex-start',
    height: PxToDp(64),
    marginLeft: PxToDp(20),
  },
  right1: {
    marginBottom: PxToDp(8),
    color: '#666',
    fontSize: PxToDp(14),
  },
  right2: {
    color: '#999',
    fontSize: PxToDp(14),
  },
  recomendWrapper: {
    width: PxToDp(355),
    height: PxToDp(205),
    marginTop: PxToDp(14),
  },
  recomendList: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    width: PxToDp(355),
    height: PxToDp(64),
    marginBottom: PxToDp(6),
    paddingLeft: PxToDp(28),
    backgroundColor: '#fff',
  },
  titleTop: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
});

export default AddCarModel;
